#ifndef _COMM_BUFFER_H_
#define _COMM_BUFFER_H_

#ifdef __cplusplus
extern "C" {
#endif

#include <stdlib.h>

typedef struct buffer buffer;

buffer * buffer_create(int max_size);
void buffer_destory(buffer * buf);

void * buffer_read_ptr(buffer * buf);
size_t buffer_read_length(buffer * buf);

void * buffer_write_ptr(buffer * buf, size_t min_len);
size_t buffer_write_length(buffer * buf);

int buffer_write(buffer * buf, const void * bin, size_t len); 
// 不会写入结尾的0
int buffer_printf(buffer * buf, const char * fmt, ...);

int buffer_read(buffer * buf, void * bin, size_t len); 
int buffer_scanf(buffer * buf, const char * fmt, ...);

int buffer_write_char(buffer * buf, char c);
int buffer_read_char(buffer * buf, char * c);

int buffer_write_short(buffer * buf, short s);
int buffer_read_short(buffer * buf, short * s);

int buffer_write_int(buffer * buf, int i);
int buffer_read_int(buffer * buf, int * i);

#define IMPLEMENT_BUFFER_TYPE(T) \
    static int buffer_write_##T(buffer * buf, T t) {  \
        return buffer_write(buf, &t, sizeof(T)); \
    } \
    static int buffer_read_##T(buffer * buf, T * t) {  \
        if (buffer_length(buf) < sizeof(T)) return -1; \
        return buffer_read(buf, t, sizeof(T)); \
    }


#ifdef __cplusplus
}
#endif

#endif
